package com.fullertontech.framework.dubbo.filter;

import java.util.List;
import org.apache.dubbo.rpc.Filter;
import org.apache.dubbo.rpc.Invocation;
import org.apache.dubbo.rpc.Invoker;
import org.apache.dubbo.rpc.Result;
import org.apache.dubbo.rpc.RpcContext;
import org.apache.dubbo.rpc.RpcException;
import org.apache.dubbo.rpc.RpcResult;
import com.fullertontech.framework.logger.Logger;

public class ProvideFilter implements Filter {

	private List<String> ipBlackList;

	@Override
	public Result invoke(Invoker<?> invoker, Invocation invocation) throws RpcException {

		Result result = invoker.invoke(invocation);

		String clientIp = RpcContext.getContext().getRemoteHost();
		Logger.debug("访问ip为{}", clientIp);

		if (ipBlackList != null && ipBlackList.contains(clientIp)) {
			Logger.debug("黑名单禁用IP{}", clientIp);
			return result;
		}

		if (result.hasException()) {
			Throwable exception = result.getException();
			Logger.error("dubbo捕捉异常:{}",exception.toString());
			if (exception instanceof Exception) {
				Logger.error("调用方法{}出现自定义异常,请求参数为:{},异常信息为:{}", invocation.getMethodName(), invocation.getArguments(), exception.getMessage());
				return result;
			}
			Logger.error("调用方法{}出现异常,请求参数为:{},异常信息为:{}", invocation.getMethodName(), invocation.getArguments(), exception.getMessage());
			return new RpcResult(exception);
		}
		return result;
	}

}